/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.mobileweb;

import app.Const;
import app.interceptors.MobileWxMemberInterceptor;
import app.models.gift.Exchange;
import app.models.gift.Gift;
import app.models.member.Member;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.kit.common.RandomStringKit;
import com.jfinal.aop.Before;

/**
 * <p>
 * 礼品兑换接口.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-06-06 10:45
 * @since JDK 1.6
 */
@Before(MobileWxMemberInterceptor.class)
public class ExchangeController extends BasicController {

    /**
     * The index route.
     *
     * /mobileweb/exchange/giftId?mid=2
     */
    public void index() {
        int gift_id = getParaToInt();

        // get gift information.
        Gift gift = Gift.dao.findById(gift_id);
        if (gift == null) {
            renderJson(AjaxMessage.failure("礼品无法找到，请确认"));
            return;
        }

        // get member information
        long member_id = getParaToLong(Const.MEMBER_PARAM, 0l);
        Member member = Member.dao.findById(member_id);

        if (member == null) {
            renderJson(AjaxMessage.failure("会员不存在"));
            return;
        }

        // check integral
        double gift_integral = gift.getNumber("intergral").doubleValue();
        // surplus integral
        double member_integral = member.getNumber("surplus").doubleValue();
        if (member_integral < gift_integral) {
            renderJson(AjaxMessage.failure("会员积分不足以兑换该礼物"));
        } else {
            final String voucher = RandomStringKit.randomAlphaNumeric(4);
            final boolean exchange = Exchange.dao.exchange(gift, member, voucher);
            if (exchange) {
                // jifen yukou
                boolean success = Member.dao.optIntegral(member_id, false, gift_integral, gift.getStr("name") + "-礼品兑换积分");
                if (success) {
                    renderSuccess();
                } else {
                    renderJson(AjaxMessage.failure("兑换失败"));
                }
            } else {
                renderJson(AjaxMessage.failure("兑换失败"));
            }
        }
    }

    public void ok() {
        render("ok.ftl");
    }
}